<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.failureTime')}}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="dataPickerType === 'monthrange'"
          class="business-date-picker business-select-mr"
          v-model="formData.monthTime"
          type="monthrange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          :clearable="false">
        </el-date-picker>
        <el-date-picker
          v-if="dataPickerType === 'daterange'"
          class="business-date-picker"
          v-model="formData.dateTime"
          type="daterange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select">
        <span>OEM：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="OEM" 
          filterable
          @change="chooseOEM"
          :clearable="true"
          style="width: 180px">
          <el-option v-for="item in tagList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.systemKeyword.customer')}}：</span>
        <biz-search-customer-select style="width: 180px" :multiple="true" :value="customerIdList" @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true"  :placeholder="$t('report.common.allCustomer')"
        />
      </div>
      <div class="charts-search-select">
        <span>{{ $t('report.mtbtSelect.cause')}}：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="ssbReasons" 
          multiple
          filterable
          :clearable="true"
          style="width: 180px">
          <el-option v-for="item in ssbReasonsList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.productType')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.catalogIds" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in productTypeList" :key="item.id" :label="item.catalogName" :value="item.id"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.driverType')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="driveTypes" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in driveTypesList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.eographicalLocation')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="positions" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in positionsList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.powerSupplyType')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="backupPowerTypes" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in backupPowerTypesList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.failureStopCause')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.causeOfFailures" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in failureReasons" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.fanStatus')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="fanStatus" 
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in fanStatusList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>

    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { lastDayOfMonth, firstDayOfMonth, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { t } from '@src/locales';
import http from 'src/util/HttpUtil';  
import { 
  getCustomerOEMDatabase,
  getProductTypes,
  getFailureReasons,
  getAllSelectDataList 
} from 'src/api/ssbReports';   
import { getCustomerList } from '@src/api/CustomerApi'
 
export default {
  name: 'product-fault-select',
  data() {
    return {
      formData:{
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        catalogIds: [], // 产品类型Ids
        causeOfFailures:[], // 故障原因
        dataType: 'month', // 日月维度
      },
      OEM:[],
      customerIdList:[],
      ssbReasons: [],
      driveTypes: [],
      positions: [],
      backupPowerTypes: [],
      fanStatus: [],
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day2'),
          value:'day'
        },
      ],
      tagList: [], // OEM列表
      userList: [], // 客户列表
      ssbReasonsList: [], // SSB原因列表
      driveTypesList: [], // 驱动器类型列表
      positionsList: [], // 地理位置列表
      backupPowerTypesList: [], // 后备电源类型列表
      fanStatusList: [], // 风机状态
      failureReasons:[],
      productTypeList:[],
      OEMFieldName:'',
      planType:'plan-a',
      pageEnum:{
        'plan-a':{
          exportName:t('report.productFaultChart.malfunctionNum')
        },
        'plan-b':{
          exportName:t('report.productFaultChart.malfunctionRate')
        }
      }
    }
  },
  computed:{
    dataPickerType(){
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  created() {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    
    this.getRequestParam()
  },
  methods: {
    getOemList(){
      return getCustomerOEMDatabase().then(res=>{
        if(res.code == 0){
          this.tagList = res.data.database
          this.OEMFieldName = res.data.fieldName
          // this.OEM = res.data.database[0] || ''
        }
      })
    },
    fetchCustomer(params){
      if (this.OEM) {
        params['conditions'] = [{property:this.OEMFieldName, value:this.OEM, key:null, operator:'eq'}]
      } else {
        params['conditions'] = []
      }
      return getCustomerList({...params})
    },
    chooseCustomer(value){
      this.customerIdList = value
      this.getProductTypes()
    },
    chooseOEM(){
      this.customerIdList = []
      this.productTypeList = []
      this.formData.catalogIds = []
    },
    getProductTypes(){
      let ids = this.customerIdList.map(item=>{
        return item.id
      })
      getProductTypes(ids).then(res=>{
        if(res.code === 0){
          this.productTypeList = res.data
        }
      })
    },
    getReasons(){
      return getFailureReasons().then(res=>{
        if(res.code === 0){
          this.failureReasons = res.data
        }
      })
    },
    handlerSearchClick(){
      this.getData()
    },
    /**
     * @des 初始化搜索所需数据
     */
    async getRequestParam () {
      // 影响报表内容的需要放在arr
      let arr = [];
      arr.push(this.getOemList());
    
  
      this.getReasons()
      this.getProductTypes()
      await getAllSelectDataList().then(res => {
        if(res.code == 0){
          let { ssbReasons = [], driveTypes = [], positions = [], backupPowerTypes = [], fanStatus = [] } = res.data || {}
          this.ssbReasonsList = ssbReasons
          this.driveTypesList = driveTypes
          this.positionsList = positions
          this.backupPowerTypesList = backupPowerTypes
          this.fanStatusList = fanStatus
          this.ssbReasons = this.ssbReasonsList?.slice(0, 1) || []
        }
      })
      Promise.all(arr).then(() => {
        this.getData()
      })
    },
    getSearchParams(){
      const { OEM, ssbReasons, driveTypes, positions, backupPowerTypes, fanStatus, customerIdList } = this;
      const { dataType, monthTime, dateTime, catalogIds, causeOfFailures } = this.formData
      let params = {
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        catalogIds,
        causeOfFailures,
        timeDimension:dataType,
        customerIds:customerIdList.map(item=>{
          return item.id
        }),
        ssbReasons,
        driveTypes,
        positions,
        backupPowerTypes,
        fanStatus,
        oem:OEM ? OEM : '',
      }
      return params;
    },
    getData(){
      const params = this.getSearchParams()
      this.$emit('change-loading', {type:1, state:true})
      http.post(this.planType == 'plan-a' ? '/api/ssbreport/outside/productFault/faultNum' : '/api/ssbreport/outside/productFault/faultProportion', params).then(res=>{
        if(res.code == 0){
          this.$emit('updateData', {data:res.data, haveUsers: res.data?.length > 0})
        }else{
          this.$message.error(res.message)
        }
      }).finally(()=>{
        
        this.$emit('change-loading', {type:1, state:false})
      })
    },
    changeType(val){
      this.planType = val
      this.getData()
    },
    export(){
      this.$emit('change-loading', {type:2, state:true})
      const params = this.getSearchParams();
      params.isExport = true;
      http.post('/api/ssbreport/outside/productFault/faultExport', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        let des_ = '';
        try{
          const item_ = this.pageEnum[this.planType];
          des_ = `-${item_.exportName}`;
        }catch(err){
          console.warn('try catch erro export')
        }
        link.download = `${this.$t('frameHeader.tabMap.personnelPerformance')}${des_}`;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{
        this.$emit('change-loading', {type:2, state:false})

      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
</style>